package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.sys.entity.ApprovalFlows;
import com.example.CarManagement.sys.mapper.ApprovalFlowsMapper;
import com.example.CarManagement.sys.service.IApprovalFlowsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批流程定义表，定义不同类型的用车申请的审批流程 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-17
 */
@Service
public class ApprovalFlowsServiceImpl extends ServiceImpl<ApprovalFlowsMapper, ApprovalFlows> implements IApprovalFlowsService {

    public Result<?> add(ApprovalFlows approvalFlows) {
        // 判断是否存在

        List<ApprovalFlows> flows = this.baseMapper.selectList(null);

        LambdaQueryWrapper<ApprovalFlows> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApprovalFlows::getName, approvalFlows.getName());
        ApprovalFlows oldFlows = this.baseMapper.selectOne(queryWrapper);

        if (oldFlows != null) {
            return Result.fail("该流程已存在");
        }

        approvalFlows.setId(UUID.randomUUID().toString());
        approvalFlows.setCreatedAt(LocalDateTime.now());
        approvalFlows.setUpdatedAt(LocalDateTime.now());
        approvalFlows.setStepNumber(flows.size() + 1);

        this.baseMapper.insert(approvalFlows);

        return Result.success("添加成功");



    }

    public Result<?> deleteFlows(String id) {
        // 删除流程
        this.baseMapper.deleteById(id);
        // 更新其他流程的步骤

        // 获取所有剩余流程并按 stepNumber 升序排序
        List<ApprovalFlows> flows = this.baseMapper.selectList(null).stream().sorted(Comparator.comparingInt(ApprovalFlows::getStepNumber)).collect(Collectors.toList());

        // 重新设置 stepNumber 使其连续
        for (int i = 0; i < flows.size(); i++) {
            ApprovalFlows flow = flows.get(i);
            flow.setStepNumber(i + 1); // 从1开始连续递增
            this.baseMapper.updateById(flow);
        }

        return Result.success();
    }
}
